<template>
	<view class="consumption-record-container">
		<!-- 自定义导航栏 -->
		<view class="custom-navbar">
			<view class="navbar-left">
				<uni-icons type="left" size="20" @click="goBack"></uni-icons>
			</view>
			<view class="navbar-title">消费记录</view>
			<view class="navbar-right">
				<uni-icons type="calendar" size="20" @click="showDatePicker"></uni-icons>
			</view>
		</view>
		
		<!-- 统计卡片 -->
		<view class="stats-card">
			<view class="stats-item">
				<text class="stats-label">本月消费</text>
				<text class="stats-value">¥{{ monthlyTotal }}</text>
			</view>
			<view class="stats-divider"></view>
			<view class="stats-item">
				<text class="stats-label">累计消费</text>
				<text class="stats-value">¥{{ totalAmount }}</text>
			</view>
		</view>
		
		<!-- 筛选标签 -->
		<view class="filter-tabs">
			<view class="tabs-container">
				<view 
					class="tab-item" 
					:class="{ active: currentFilter === filter.key }"
					v-for="filter in filterList" 
					:key="filter.key"
					@click="switchFilter(filter.key)"
				>
					<text class="tab-text">{{ filter.name }}</text>
				</view>
			</view>
		</view>
		
		<!-- 消费记录列表 -->
		<view class="record-list">
			<view v-if="currentRecords.length === 0" class="empty-records">
				<uni-icons type="list" size="48" color="#ccc"></uni-icons>
				<text class="empty-text">暂无消费记录</text>
			</view>
			
			<view 
				v-else
				class="record-item" 
				v-for="(record, index) in currentRecords" 
				:key="index"
				@click="viewRecordDetail(record)"
			>
				<view class="record-left">
					<view class="service-icon" :class="record.serviceType">
						<uni-icons :type="getServiceIcon(record.serviceType)" size="20" color="#ffffff"></uni-icons>
					</view>
				</view>
				<view class="record-center">
					<view class="record-title">{{ record.title }}</view>
					<view class="record-desc">{{ record.description }}</view>
					<view class="record-time">{{ record.time }}</view>
				</view>
				<view class="record-right">
					<view class="record-amount" :class="getAmountClass(record)">{{ formatAmount(record) }}</view>
					<view class="record-status" :class="record.status">
						<text class="status-text">{{ getStatusText(record.status) }}</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 加载更多 -->
		<view v-if="hasMore && currentRecords.length > 0" class="load-more" @click="loadMoreRecords">
			<text class="load-more-text">加载更多</text>
		</view>
		
		<!-- 日期选择器弹窗 -->
		<uni-popup ref="datePicker" type="bottom">
			<view class="date-picker-container">
				<view class="picker-header">
					<text class="picker-title">选择时间范围</text>
					<uni-icons type="close" size="20" @click="closeDatePicker"></uni-icons>
				</view>
				<picker-view 
					class="picker-view" 
					:value="datePickerValue" 
					@change="onDatePickerChange"
				>
					<picker-view-column>
						<view class="picker-item" v-for="year in years" :key="year">{{ year }}年</view>
					</picker-view-column>
					<picker-view-column>
						<view class="picker-item" v-for="month in months" :key="month">{{ month }}月</view>
					</picker-view-column>
				</picker-view>
				<view class="picker-actions">
					<view class="action-btn cancel" @click="closeDatePicker">取消</view>
					<view class="action-btn confirm" @click="confirmDatePicker">确定</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import uniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue';
	import uniPopup from '@dcloudio/uni-ui/lib/uni-popup/uni-popup.vue';
	import { consumptionApi } from '@/api/index.js';
	
	export default {
		components: { 
			uniIcons,
			uniPopup
		},
		data() {
			return {
				currentFilter: 'all',
				filterList: [
					{ key: 'all', name: '全部' },
					{ key: 'fuel', name: '加油' },
					{ key: 'carwash', name: '洗车' },
					{ key: 'repair', name: '维修' },
					{ key: 'maintenance', name: '保养' },
					{ key: 'rescue', name: '救援' }
				],
				allRecords: [],
				hasMore: true,
				datePickerValue: [0, 0],
				years: [],
				months: [],
				selectedYear: new Date().getFullYear(),
				selectedMonth: new Date().getMonth() + 1,
				monthlyTotal: 0,
				totalAmount: 0,
				loading: false,
				useMockData: false
			};
		},
		computed: {
			currentRecords() {
				if (this.currentFilter === 'all') {
					return this.allRecords;
				}
				return this.allRecords.filter(record => record.serviceType === this.currentFilter);
			}
		},
		onLoad() {
			this.initData();
		},
		methods: {
			// 初始化数据
			async initData() {
				try {
					this.loading = true;
					
					console.log('开始初始化消费记录数据...');
					
					// 使用新的API接口获取所有用户的消费记录
					const recordsResult = await consumptionApi.getAllConsumptionRecords();
					const statsResult = await consumptionApi.getConsumptionStatistics(1); // 暂时保持用户1的统计
					
					console.log('消费记录API响应详情:', {
						recordsResult: recordsResult,
						statsResult: statsResult,
						recordsCode: recordsResult?.code,
						recordsData: recordsResult?.data,
						recordsDataLength: recordsResult?.data?.length,
						recordsDataType: Array.isArray(recordsResult?.data)
					});
					
					// 检查API响应
					if (recordsResult && recordsResult.code === 200 && recordsResult.data) {
						console.log('后端数据获取成功，开始转换数据格式...');
						
						// 转换后端数据格式为前端期望的格式
						this.allRecords = this.convertBackendData(recordsResult.data);
						
						console.log('数据转换完成，转换后的记录:', this.allRecords);
						
						// 计算所有用户的总消费金额（消费为正数，退款为负数）
						const totalAmount = this.allRecords.reduce((sum, record) => {
							const amount = parseFloat(record.originalAmount || record.amount || 0);
							console.log(`记录: ${record.title || record.remark}, 原始金额: ${amount}, 当前累计: ${sum}, 累加后: ${sum + amount}`);
							return sum + amount;
						}, 0);
						
						// 计算纯消费金额（不包括退款）
						const pureConsumption = this.allRecords.reduce((sum, record) => {
							const amount = parseFloat(record.originalAmount || record.amount || 0);
							// 只计算正数（消费），不包括负数（退款）
							return amount > 0 ? sum + amount : sum;
						}, 0);
						
						this.monthlyTotal = pureConsumption; // 本月消费显示纯消费金额
						this.totalAmount = pureConsumption;  // 累计消费显示纯消费金额
						this.useMockData = false;
						
						console.log('成功从后端获取所有消费记录数据');
						console.log('消费记录数量:', this.allRecords.length);
						console.log('总消费金额（已处理退款）:', this.totalAmount);
					} else {
						console.log('后端数据获取失败，响应详情:', {
							hasResult: !!recordsResult,
							code: recordsResult?.code,
							hasData: !!recordsResult?.data,
							dataType: typeof recordsResult?.data,
							isArray: Array.isArray(recordsResult?.data)
						});
						console.log('使用模拟数据');
						// 使用模拟数据
						await this.loadMockData();
					}
				} catch (error) {
					console.error('初始化数据失败:', error);
					await this.loadMockData();
				} finally {
					this.loading = false;
				}
			},
			
			// 加载模拟数据
			async loadMockData() {
				try {
					const recordsResult = await consumptionApi.getMockConsumptionRecords(1);
					const statsResult = await consumptionApi.getMockConsumptionStatistics(1);
					
					if (recordsResult && recordsResult.success) {
						this.allRecords = recordsResult.data;
						this.useMockData = true;
						
						// 计算纯消费金额（不包括退款）
						const pureConsumption = this.allRecords.reduce((sum, record) => {
							const amount = parseFloat(record.amount || 0);
							// 只计算正数（消费），不包括负数（退款）
							return amount > 0 ? sum + amount : sum;
						}, 0);
						
						this.monthlyTotal = pureConsumption;
						this.totalAmount = pureConsumption;
					}
					
					if (statsResult && statsResult.success) {
						// 如果API返回的统计数据是负数，使用计算出的纯消费金额
						const apiMonthlyTotal = statsResult.data.monthlyTotal || 0;
						const apiTotalAmount = statsResult.data.totalAmount || 0;
						
						this.monthlyTotal = apiMonthlyTotal > 0 ? apiMonthlyTotal : this.monthlyTotal;
						this.totalAmount = apiTotalAmount > 0 ? apiTotalAmount : this.totalAmount;
					}
					
					console.log('使用模拟数据，纯消费金额:', this.totalAmount);
				} catch (error) {
					console.error('加载模拟数据失败:', error);
				}
			},
			
			// 转换后端数据格式
			convertBackendData(backendData) {
				if (!Array.isArray(backendData)) {
					console.log('后端数据不是数组格式:', backendData);
					return [];
				}
				
				return backendData.map(record => {
					// 根据后端数据字段进行转换
					const convertedRecord = {
						id: record.recordId || record.id || record.consumptionId,
						title: this.extractServiceTitle(record.remark || record.description || record.title),
						description: record.remark || record.description || '暂无描述',
						amount: Math.abs(record.amount || 0).toFixed(2),
						time: record.recordTime || record.record_time || record.createTime || record.create_time || new Date().toLocaleString(),
						serviceType: this.mapServiceType(record.remark || record.description || record.title),
						status: this.mapStatus(record.recordType || record.record_type, record.amount || 0),
						orderNo: record.orderNumber || record.order_number || record.orderNo || 'N/A',
						merchantName: this.extractMerchantName(record.remark || record.description || record.title),
						originalAmount: record.amount || 0,
						isRefund: (record.amount || 0) < 0
					};
					
					console.log('转换后的记录:', convertedRecord);
					return convertedRecord;
				});
			},
			
			// 提取服务标题
			extractServiceTitle(remark) {
				if (!remark) return '消费记录';
				
				// 从备注中提取服务类型
				if (remark.includes('洗车')) return '专业洗车服务';
				if (remark.includes('打蜡')) return '汽车美容服务';
				if (remark.includes('换胎')) return '轮胎更换服务';
				if (remark.includes('保养')) return '汽车保养服务';
				if (remark.includes('维修')) return '汽车维修服务';
				if (remark.includes('加油')) return '就近加油服务';
				if (remark.includes('救援')) return '应急救援服务';
				if (remark.includes('退款')) return '退款服务';
				
				return '其他服务';
			},
			
			// 提取商户名称
			extractMerchantName(remark) {
				if (!remark) return '未知商家';
				
				// 从备注中提取商户名称
				if (remark.includes('大美汽车维修店')) return '大美汽车维修店';
				if (remark.includes('小美汽车美容店')) return '小美汽车美容店';
				if (remark.includes('中美汽车维修店')) return '中美汽车维修店';
				if (remark.includes('中国石油')) return '中国石油加油站';
				if (remark.includes('退款')) return '系统退款';
				
				return '未知商家';
			},
			
			// 映射服务类型
			mapServiceType(remark) {
				if (!remark) return 'other';
				
				if (remark.includes('洗车')) return 'carwash';
				if (remark.includes('打蜡')) return 'carwash';
				if (remark.includes('换胎')) return 'repair';
				if (remark.includes('保养')) return 'maintenance';
				if (remark.includes('维修')) return 'repair';
				if (remark.includes('加油')) return 'fuel';
				if (remark.includes('救援')) return 'rescue';
				if (remark.includes('退款')) return 'refund';
				
				return 'other';
			},
			
			// 映射状态
			mapStatus(recordType, amount) {
				// 根据金额正负判断状态，而不是record_type
				if (amount < 0) {
					return 'refunded';  // 负数表示退款
				} else {
					return 'completed'; // 正数表示消费完成
				}
			},
			
			// 切换筛选条件
			async switchFilter(filterKey) {
				this.currentFilter = filterKey;
				
				// 如果使用模拟数据，重新筛选
				if (this.useMockData) {
					await this.loadMockData();
				}
			},
			
			// 加载更多记录
			async loadMoreRecords() {
				if (this.loading) return;
				
				try {
					this.loading = true;
					
					// 这里可以实现分页加载逻辑
					// 暂时只是显示加载状态
					await new Promise(resolve => setTimeout(resolve, 1000));
					
					uni.showToast({
						title: '暂无更多数据',
						icon: 'none'
					});
				} catch (error) {
					console.error('加载更多失败:', error);
				} finally {
					this.loading = false;
				}
			},
			
			// 查看记录详情
			viewRecordDetail(record) {
				const statusText = this.getStatusText(record.status);
				const amountText = record.isRefund ? `退款 ¥${record.amount}` : `消费 ¥${record.amount}`;
				
				uni.showModal({
					title: '消费详情',
					content: `订单号：${record.orderNo}\n服务类型：${this.getServiceTypeName(record.serviceType)}\n${amountText}\n时间：${record.time}\n状态：${statusText}\n商户：${record.merchantName}`,
					showCancel: false,
					confirmText: '知道了'
				});
			},
			
			// 获取服务类型名称
			getServiceTypeName(type) {
				const typeMap = {
					'fuel': '加油',
					'carwash': '洗车',
					'repair': '维修',
					'maintenance': '保养',
					'rescue': '救援',
					'refund': '退款',
					'other': '其他'
				};
				return typeMap[type] || '其他';
			},
			
			// 获取状态文本
			getStatusText(status) {
				const statusMap = {
					'completed': '已完成',
					'refunded': '已退款',
					'pending': '待处理',
					'cancelled': '已取消'
				};
				return statusMap[status] || '未知';
			},
			
			// 获取服务图标
			getServiceIcon(type) {
				const iconMap = {
					'fuel': 'fuel',
					'carwash': 'water',
					'repair': 'settings',
					'maintenance': 'gear',
					'rescue': 'car',
					'refund': 'close',
					'other': 'help'
				};
				return iconMap[type] || 'help';
			},
			
			// 格式化金额显示
			formatAmount(record) {
				if (record.isRefund) {
					return `退款 ¥${record.amount}`;
				}
				return `¥${record.amount}`;
			},
			
			// 获取金额样式类
			getAmountClass(record) {
				return record.isRefund ? 'refund-amount' : 'consumption-amount';
			},
			
			// 显示日期选择器
			showDatePicker() {
				this.$refs.datePicker.open();
			},
			
			// 关闭日期选择器
			closeDatePicker() {
				this.$refs.datePicker.close();
			},
			
			// 日期选择器变化
			onDatePickerChange(e) {
				this.datePickerValue = e.detail.value;
			},
			
			// 确认日期选择
			confirmDatePicker() {
				const year = this.years[this.datePickerValue[0]];
				const month = this.months[this.datePickerValue[1]];
				
				this.selectedYear = year;
				this.selectedMonth = month;
				
				// 根据选择的日期筛选数据
				this.filterRecordsByDate(year, month);
				
				this.closeDatePicker();
			},
			
			// 根据日期筛选记录
			filterRecordsByDate(year, month) {
				// 这里可以实现按日期筛选的逻辑
				console.log(`筛选 ${year}年${month}月 的数据`);
			},
			
			// 返回上一页
			goBack() {
				uni.navigateBack();
			}
		},
		
		// 生命周期
		created() {
			// 生成年份和月份数据
			const currentYear = new Date().getFullYear();
			for (let i = currentYear - 5; i <= currentYear + 1; i++) {
				this.years.push(i);
			}
			
			for (let i = 1; i <= 12; i++) {
				this.months.push(i);
			}
		}
	};
</script>

<style lang="scss" scoped>
	.consumption-record-container {
		background-color: #f5f5f5;
		min-height: 100vh;
	}
	
	// 自定义导航栏
	.custom-navbar {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 44px 16px 12px 16px;
		background-color: #ffffff;
		border-bottom: 1px solid #f0f0f0;
		
		.navbar-left {
			width: 40px;
		}
		
		.navbar-title {
			font-size: 18px;
			font-weight: bold;
			color: #333333;
		}
		
		.navbar-right {
			width: 40px;
			display: flex;
			justify-content: flex-end;
		}
	}
	
	// 统计卡片
	.stats-card {
		display: flex;
		background-color: #ffffff;
		margin: 12px 16px;
		border-radius: 8px;
		padding: 20px;
		
		.stats-item {
			flex: 1;
			display: flex;
			flex-direction: column;
			align-items: center;
			
			.stats-label {
				font-size: 12px;
				color: #666666;
				margin-bottom: 8px;
			}
			
			.stats-value {
				font-size: 20px;
				font-weight: bold;
				color: #333333;
			}
		}
		
		.stats-divider {
			width: 1px;
			background-color: #f0f0f0;
			margin: 0 20px;
		}
	}
	
	// 筛选标签
	.filter-tabs {
		background-color: #ffffff;
		margin-bottom: 12px;
		
		.tabs-container {
			display: flex;
			padding: 0 16px;
			
			.tab-item {
				flex: 1;
				padding: 16px 8px;
				text-align: center;
				position: relative;
				
				.tab-text {
					font-size: 14px;
					color: #666666;
				}
				
				&.active {
					.tab-text {
						color: #007AFF;
						font-weight: bold;
					}
					
					&::after {
						content: '';
						position: absolute;
						bottom: 0;
						left: 50%;
						transform: translateX(-50%);
						width: 20px;
						height: 2px;
						background-color: #007AFF;
						border-radius: 1px;
					}
				}
			}
		}
	}
	
	// 消费记录列表
	.record-list {
		.empty-records {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: 60px 20px;
			
			.empty-text {
				margin-top: 16px;
				font-size: 14px;
				color: #999999;
			}
		}
		
		.record-item {
			display: flex;
			align-items: center;
			background-color: #ffffff;
			margin: 0 16px 12px 16px;
			border-radius: 8px;
			padding: 16px;
			
			.record-left {
				margin-right: 12px;
				
				.service-icon {
					width: 40px;
					height: 40px;
					border-radius: 20px;
					display: flex;
					align-items: center;
					justify-content: center;
					
					&.fuel {
						background-color: #ff6b6b;
					}
					
					&.carwash {
						background-color: #4ecdc4;
					}
					
					&.repair {
						background-color: #45b7d1;
					}
					
					&.maintenance {
						background-color: #96ceb4;
					}
					&.rescue {
						background-color: #f56c6c;
					}
				}
			}
			
			.record-center {
				flex: 1;
				
				.record-title {
					font-size: 16px;
					font-weight: bold;
					color: #333333;
					margin-bottom: 4px;
				}
				
				.record-desc {
					font-size: 12px;
					color: #666666;
					margin-bottom: 4px;
				}
				
				.record-time {
					font-size: 12px;
					color: #999999;
				}
			}
			
			.record-right {
				text-align: right;
				
				.record-amount {
					font-size: 18px;
					font-weight: bold;
					color: #ff4d4f;
					margin-bottom: 4px;
					
					&.refund-amount {
						color: #52c41a;
					}
					
					&.consumption-amount {
						color: #ff4d4f;
					}
				}
				
				.record-status {
					display: inline-block;
					padding: 2px 6px;
					border-radius: 8px;
					font-size: 10px;
					
					&.completed {
						background-color: #e8f5e8;
						color: #52c41a;
					}
					
					&.pending {
						background-color: #fff7e6;
						color: #fa8c16;
					}
					
					&.cancelled {
						background-color: #fff2f0;
						color: #ff4d4f;
					}
					
					.status-text {
						font-weight: bold;
					}
				}
			}
		}
	}
	
	// 加载更多
	.load-more {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 16px;
		background-color: #ffffff;
		
		.load-more-text {
			font-size: 14px;
			color: #007AFF;
		}
	}
	
	// 日期选择器
	.date-picker-container {
		background-color: #ffffff;
		border-radius: 16px 16px 0 0;
		padding: 20px;
		
		.picker-header {
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-bottom: 20px;
			
			.picker-title {
				font-size: 16px;
				font-weight: bold;
				color: #333333;
			}
		}
		
		.picker-view {
			height: 200px;
			margin-bottom: 20px;
			
			.picker-item {
				display: flex;
				align-items: center;
				justify-content: center;
				height: 40px;
				font-size: 16px;
				color: #333333;
			}
		}
		
		.picker-actions {
			display: flex;
			gap: 12px;
			
			.action-btn {
				flex: 1;
				padding: 12px;
				border-radius: 8px;
				text-align: center;
				font-size: 14px;
				font-weight: bold;
				
				&.cancel {
					background-color: #f5f5f5;
					color: #666666;
				}
				
				&.confirm {
					background-color: #007AFF;
					color: #ffffff;
				}
			}
		}
	}
</style> 